package cn.emailChat.ai.config;

import cn.emailChat.ai.filterchain.FilterHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.List;

/**
 * @Description 责任链配置：将所有 FilterHandler 按 @Order 排序后串成一条链
 * @Author susu
 * @Date 2025/8/20
 */
@Slf4j
@Configuration
public class FilterChainConfig {

    /**
     * 收集所有 FilterHandler Bean，按 @Order 排序，串成链并返回链头
     */
    @Bean
    public FilterHandler filterChain(List<FilterHandler> handlers) {
        // 按 @Order 排序
        handlers.sort(AnnotationAwareOrderComparator.INSTANCE);

        // 串链：handler1.setNext(handler2).setNext(handler3) ...
        for (int i = 0; i < handlers.size() - 1; i++) {
            handlers.get(i).setNext(handlers.get(i + 1));
        }

        log.info("[FilterChain] 已装配处理链：{} 个节点", handlers.size());
        // 返回链头（第一个处理器），已有兜底策略，用不为空
        return handlers.get(0);
    }
}